package com.free.framework.lib.utils;

import android.text.TextUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author free
 * @date 16/9/10
 */
public class MD5Util {

    public static String toMD5(String str) {

        try {
            MessageDigest localMessageDigest = MessageDigest.getInstance("MD5");
            localMessageDigest.update(str.getBytes());
            byte[] arrayOfByte = localMessageDigest.digest();
            StringBuffer localStringBuffer = new StringBuffer();
            for (int i = 0; i < arrayOfByte.length; i++) {
                int j = 0xFF & arrayOfByte[i];
                if (j < 16)
                    localStringBuffer.append("0");
                localStringBuffer.append(Integer.toHexString(j));
            }
            return localStringBuffer.toString();
        } catch (NoSuchAlgorithmException localNoSuchAlgorithmException) {

        }
        return "";
    }


    private static Map<String, String> md5ValueCache = new HashMap<String, String>();

    public static String getMD5ValueByUid(String uid) {

        String result = md5ValueCache.get(uid);
        if (TextUtils.isEmpty(result)) {
            md5ValueCache.clear();
            if (!TextUtils.isEmpty(uid)) {
                result = MD5Util.toMD5(uid);
                md5ValueCache.put(uid, result);
            }
        }
        return result;

    }

}
